package com.libgdxbar.pvzlikegame.objects;

import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.libgdxbar.pvzlikegame.AssetsLoader;
import com.libgdxbar.pvzlikegame.entities.LocationEntity;
import com.libgdxbar.pvzlikegame.systems.animation.Animator;
import com.libgdxbar.pvzlikegame.systems.animation.GdxAnimation;
import org.libgdxbar.projects.interfaces.animation.IAnimationListener;
import org.libgdxbar.projects.interfaces.animation.IAnimator;
import org.libgdxbar.projects.interfaces.animation.TrackEntry;
import org.libgdxbar.projects.interfaces.renderer.IBatchRender;

import java.util.Objects;

public class SampleAnimationPlant extends LocationEntity implements IAnimator, IBatchRender {

	private Animator animator = new Animator();
	private final Texture animationTexture = AssetsLoader.getInstance().get("plant-stub-animation.png", Texture.class);

	public SampleAnimationPlant(float x, float y) {
		super(x, y);
		TextureRegion[][] animationRegions = TextureRegion.split(animationTexture, 64, 64);
		animator.addAnimator(new GdxAnimation("idle", new Animation<TextureRegion>(1 / 8f, animationRegions[0]) {{
			setPlayMode(PlayMode.LOOP);
		}}));
		Animator.TrackEntry attackEntry = animator.addAnimator(new GdxAnimation("attack", new Animation<TextureRegion>(1 / 8f, animationRegions[1])));
		attackEntry.setListener(new IAnimationListener() {
			@Override
			public void onAnimationStart(TrackEntry entry) {

			}

			@Override
			public void onAnimationEnd(TrackEntry entry) {
				animator.setAnimation("idle");
			}
		});
		animator.setAnimation("idle");
	}

	@Override
	public void run(float delta) {
		super.run(delta);
		animator.update(delta);
		if (Objects.equals(animator.getAnimation().getName(), "idle")) {
			// 生成一个0到1之间的随机数
			float randomValue = MathUtils.random();
			// 检查这个随机数是否小于或等于5%
			if (randomValue <= 0.0001) {
				System.out.println("change animation to attack");
				animator.setAnimation("attack");
			}
		}
	}

	@Override
	public void render(Batch batch) {
		Vector2 position = getPosition();
		batch.draw(animator.getFrame(), position.x, position.y, 50, 50);
	}

	@Override
	public TrackEntry changeAnimation(String animationName) {
		return animator.setAnimation(animationName);
	}

}
